package com.fingard.dsp.bank.directbank.srb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.czb01.CZB01Header;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.commons.lang.StringUtils;

public class SRB01SinglePay extends SRB01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        try {

            //region 封装请求报文
            SRB01Header bankHeader = new SRB01Header();
            bankHeader.trCode = "300001";
            bankHeader.reqSeqNo = p_req1908.singleDetail.askNumber;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.autoFormat = false;
            writeCommonHeader(xmlWriter, bankHeader, false);
            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("pay_acno", p_req1908.singleDetail.payAct));                 //付款账号
            tmpXElement.addChild(new XElement("proxy_pay_acno", ""));                          //代理付款帐号
            tmpXElement.addChild(new XElement("pay_cur_code", convertCurToBank(p_req1908.singleDetail.payCur)));//付款币种
            tmpXElement.addChild(new XElement("pay_acname", p_req1908.singleDetail.payName));              //付款户名
            tmpXElement.addChild(new XElement("proxy_pay_acname", ""));                        //代理付款户名
            tmpXElement.addChild(new XElement("proxy_pay_orgname", ""));                       //代理付款开户行
            tmpXElement.addChild(new XElement("pay_accaddr", ""));                              //付款地址
            tmpXElement.addChild(new XElement("cert_type", p_req1908.singleDetail.certType));             //凭证种类
            tmpXElement.addChild(new XElement("cert_no", p_req1908.singleDetail.askNumber));                 //凭证号
            tmpXElement.addChild(new XElement("rcv_acno", p_req1908.singleDetail.recAct));                 //收款账号
            tmpXElement.addChild(new XElement("rcv_cur_code", convertCurToBank(p_req1908.singleDetail.recCur))); //收款币种
            tmpXElement.addChild(new XElement("rcv_acname", p_req1908.singleDetail.recName));             //收款户名
            tmpXElement.addChild(new XElement("rcv_accaddr", ""));                             //收款人地址
            tmpXElement.addChild(new XElement("rcv_bank_no", p_req1908.singleDetail.cnapsCode));          //收款行号
            tmpXElement.addChild(new XElement("rcv_bank_name", p_req1908.singleDetail.recBankName));     //收款行名
            tmpXElement.addChild(new XElement("amt", p_req1908.singleDetail.payAmount));                   //交易金额
            tmpXElement.addChild(new XElement("bank_flag", "1".equals(p_req1908.singleDetail.sameBnk) ? "0" : "1"));    //银行标志
            tmpXElement.addChild(new XElement("urgency_flag", "1"));                           //加急标志
            //银行要求：bank_flag 送 0 行内转账时 ares_flag 送 2； bank_flag 送 1 跨行转账时，ares_flag 送 3（普通）或者4（实时）
            tmpXElement.addChild(new XElement("area_flag", "1".equals(p_req1908.singleDetail.sameBnk) ? "2" : "4"));
            tmpXElement.addChild(new XElement("bank_kind", getBankConfig().getValueAsString("bankkind")));
            tmpXElement.addChild(new XElement("purpose", p_req1908.singleDetail.purpose));          //用途
            tmpXElement.addChild(new XElement("as_acno", ""));         //银行要求增加
            tmpXElement.addChild(new XElement("as_acname", ""));         //银行要求增加
            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndElement();  //ap
            xmlWriter.writeEndDocument();
            //endregion

            //region 发送请求报文，并获取响应报文
            String[] retStrArr = sendToBank(xmlWriter.toXmlString());
            //endregion

            //region 解析响应报文
            if (retStrArr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ext_info");
                    String succFlag = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    retDetail.respCode = "0";
                    retDetail.transState = succFlag + "+" + tmpRetCode;
                    retDetail.respInfo = StringUtils.isEmpty(tmpRetInfo) ? tmpBkReader.getFirstText("/ap/head/ret_info") : tmpRetInfo;
                    retDetail.reqSeqID = tmpBkReader.getFirstText("/ap/head/req_no");
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                    retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                }
            } else if (ConnState.FAIL.equals(retStrArr[0])) {
                retDetail.respCode = "-1";
                retDetail.respInfo = retStrArr[1];
                retDetail.transState = PaymentState.FAIL_Payment;
//                retDetail.payInfoCode = retStrArr[0];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = retStrArr[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            }
            //endregion

        } catch (Exception e) {
            retDetail = new RetAtsSglDetail();
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {

        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();

        try {

            //region 请求报文封装
            SRB01Header bankHeader = new SRB01Header();
            bankHeader.trCode = "200205";
            bankHeader.reqSeqNo = p_req1944.askNumber;

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            xmlWriter.autoFormat = false;
            writeCommonHeader(xmlWriter, bankHeader, false);//写入通用的头部节点
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("req_no", p_req1944.askNumber);
            xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(p_req1944.getBgnDateTime()));
            xmlWriter.writeElementString("cert_no", "");
            xmlWriter.writeEndElement();//body
            xmlWriter.writeEndElement();//ap
            xmlWriter.writeEndDocument();
            //endregion

            //region 发送请求报文，并获取响应报文
            String[] retStrArr = sendToBank(xmlWriter.toXmlString());
            //endregion

            if (retStrArr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    String succFlagStr = tmpBkReader.getFirstText("/ap/head/succ_flag");
                    if ("0".equals(succFlagStr)) {
                        tmpRetAtsDetail.respCode = "0";
                    /*
                    if ("0000".equals(tmpRetCode)) {
                        tmpRetAtsDetail.respCode = "0";
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                    }*/
                        tmpRetAtsDetail.reqSeqID = tmpBkReader.getFirstText("/ap/body/req_no");
                        String transStateStr = tmpBkReader.getFirstText("/ap/body/stat");
                        String errInfo = tmpBkReader.getFirstText("/ap/body/error_info");
                        tmpRetAtsDetail.transAmt = tmpBkReader.getFirstText("/ap/body/amt");
                        tmpRetAtsDetail.transState = succFlagStr + "+" + tmpRetCode + "+" + transStateStr;
                        tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
                        if (StringHelper.isNullOrEmpty(errInfo)) {
                            tmpRetAtsDetail.respInfo = tmpRetInfo;
                        } else {
                            tmpRetAtsDetail.respInfo = errInfo;
                        }
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = tmpRetInfo;
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = retStrArr[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
